<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageToods :show-before="true">
        <span slot="before">共16条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/employees/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" @click="isShowDialog = true">新增员工</el-button>
        </template>
      </PageToods>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" prop="index" />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column prop="formOfEmployment" label="聘用形式" sortable="" :formatter="formatEmployment" />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
            <template v-slot="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="账户状态" sortable="">
            <template v-slot="scope">
              <el-switch
                :value="scope.row.enableState"
                :active-value="1"
                :inactive-value="0"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRoleDialog(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :total="total" :page-size="pageConfig.size" @current-change="currentChange" />
        </el-row>
      </el-card>
      <Addemployee :is-show-dialog="isShowDialog" />
      <AssignRole ref="assignRole" :is-show-role-dialog="isShowRoleDialog" />
    </div>
  </div>
</template>

<script>
import Addemployee from '@/views/employees/components/add-employee.vue'
import AssignRole from '@/views/employees/components/assign-role.vue'
import EmployeeEnum from '@/constant/employees'
import { getEmployee, delEmployee } from '@/api/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
export default {
  components: { Addemployee, AssignRole },
  data() {
    return {
      pageConfig: {
        page: 1,
        size: 5
      },
      list: [],
      total: 0,
      isShowDialog: false,
      isShowRoleDialog: false
    }
  },
  created() {
    this.loadPage()
  },
  methods: {
    async showRoleDialog(id) {
      await this.$refs.assignRole.getUserDetail(id)
      this.isShowRoleDialog = true
    },
    async loadPage() {
      const { rows, total } = await getEmployee(this.pageConfig)
      this.list = rows.map((item, index) => {
        return {
          ...item,
          index: (this.pageConfig.page - 1) * this.pageConfig.size + index + 1
        }
      })
      this.total = total
    },
    currentChange(newPage) {
      this.pageConfig.page = newPage
      this.loadPage()
    },
    formatEmployment(row, col, val) {
      const res = EmployeeEnum.hireType.find(item => item.id === val)
      return res ? res.value : '未知'
      // 这里的返回值会替代当前的格子数据
      // return val === 1 ? '正式' : '非正式'
    },
    async exportExcel() {
      // 获取员工所有数据
      const { rows } = await getEmployee({
        page: 1,
        size: this.total
      })
      console.log(rows)
      // 定义字典, 里面以key:value 键值对的形式配对 表头和对应要拿的数据字段名
      const dict = {
        '手机号': 'mobile',
        '用户名': 'username',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment',
        '入职时间': 'timeOfEntry'
      }
      // 定表头
      const header = Object.keys(dict)
      // 来源数据格式
      // [{}{}{}]
      // map 转换
      // 目标数据格式
      // [[][][]]
      const data = rows.map(item => {
        const user = []
        for (const zhKey in dict) {
          // 遍历中文zhKey, 获取英文 enKey, 如 遍历到用户名则获取到 username
          const enKey = dict[zhKey]
          // 通过英文 enKey 在用户中拿出应该被推入到数组的数据 value,
          const value = item[enKey]
          if (enKey === 'formOfEmployment') {
            // 聘用形式特殊处理
            const obj = EmployeeEnum.hireType.find(el => el.id === value)
            user.push(obj ? obj.value : '未知')
          } else if (enKey === 'timeOfEntry') {
            // 入职时间特殊处理
            user.push(formatDate(value))
          } else {
            // 普通的数据
            user.push(value)
          }
          // user.push(item.username)
          // user.push(item.mobile)
          // user.push(item.departmentName)
          // // 特殊数据一:聘用形式特殊处理
          // const obj = EmployeeEnum.hireType.find(el => el.id === item.formOfEmployment)
          // const formOfEmployment = obj ? obj.value : '未知'
          // user.push(formOfEmployment)
          // // 特殊数据二:入职时间特殊处理
          // user.push(formatDate(item.timeOfEntry))
        }
        return user
      })
      export_json_to_excel({
        header,
        data
      })
    },
    // 删除
    async delEmployee(id) {
      try {
        // 二次询问
        await this.$confirm('确认删除吗？')
        // 发送请求
        await delEmployee(id)
        // 提示弹框
        this.$message.success('删除成功')
        // 重新渲染
        this.loadPage()
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style></style>
